package loader

import (
	"os"
	"fmt"
	"kumachan/stdlib"
)


type cachedIndex (map[string] *Module)

var stdlibModules = (func() cachedIndex {
	var idx = make(Index)
	var fs = StdFileSystem { stdlib.GetModuleFileSystem() }
	var seq = stdlib.GetModuleLoadSequence()
	var ctx = makeEntryContext()
	for _, name := range seq {
		var _, err = loadModule(name, fs, ctx, idx)
		if err != nil {
			var msg_text = err.Message().RenderConsole()
			fmt.Fprintf (
				os.Stderr,
				"%v*** Failed to Load Standard Library%v\n*\n%s\n",
				"\033[1m", "\033[0m", msg_text,
			)
			os.Exit(3)
		}
	}
	return cachedIndex(idx)
})()

func loadStdlib(idx *Index) {
	for name, mod := range stdlibModules {
		(*idx)[name] = mod
	}
}

func importStdlib(m *(map[string] *Module), s *(map[string] bool), src Index) {
	for _, name := range stdlib.GetModuleLoadSequence() {
		var mod, exists = src[name]
		if exists {
			(*m)[name] = mod
			(*s)[name] = true
		}
	}
}


